package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"novel-world/cache"
	"novel-world/models"
	"strconv"
	"time"
)

func UserRole(c *gin.Context) {
	rid := c.Query("rid")

	/*
		SELECT*FROM
		users
		LEFT JOIN user_roles ON user_roles.rid=users.id
		WHERE user_roles.rid=1
	*/
	var arr []models.User
	redis_key := "redis_userRole" + rid
	redisData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if redisData == "" {
		models.DB.Table("users").
			Joins("LEFT JOIN user_roles ON user_roles.rid=users.id").
			Where("user_roles.rid=?", rid).
			Find(&arr)
		jsondata, _ := json.Marshal(arr)
		cache.Rdb.Set(cache.Ctx, redis_key, jsondata, time.Hour*2)
	} else {
		json.Unmarshal([]byte(redisData), &arr)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": arr,
	})
}

func RoleNode(c *gin.Context) {
	nid := c.Query("nid")

	/*
		SELECT*FROM
		nodes
		LEFT JOIN role_nodes ON role_nodes.nid=nodes.id
		WHERE role_nodes.nid=1
	*/

	var arr []models.Node
	models.DB.Table("nodes").
		Joins("LEFT JOIN role_nodes ON role_nodes.nid=nodes.id").
		Where("role_nodes.nid=?", nid).
		Find(&arr)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": arr,
	})
}

func CarList(c *gin.Context) {
	page, _ := strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ := strconv.Atoi(c.DefaultQuery("pageSize", "3"))
	offset := (page - 1) * pageSize
	redis_key := "redis_list_" + strconv.Itoa(page)
	DataRed, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()

	/*
		SELECT
		car_types.cid as OrderId,
		cars.car_name as CarNamr,
		cars.car_content as CarContent,
		car_types.type_name as TypeName,
		car_types.price as Price
		FROM
		cars
		LEFT JOIN car_types ON car_types.cid=cars.id
	*/
	var arr []models.CarList
	if DataRed == "" {
		models.DB.Table("cars").
			Select(
				"car_types.cid as OrderId",
				"cars.car_name as CarNamr",
				"cars.car_content as CarContent",
				"car_types.type_name as TypeName",
				"car_types.price as Price",
			).
			Joins("LEFT JOIN car_types ON car_types.cid=cars.id").
			Offset(offset).Limit(pageSize).Debug().Find(&arr)
		jsonData, _ := json.Marshal(arr)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(DataRed), &arr)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "查询成功",
		"list": arr,
	})
}
